<template>
  <!-- 页面-菜单管理-添加 -->
  <div class="sidelip-box">
    <Form
      :model="modelForm"
      ref="menuForm"
      class="ivu-form-no-margin-bottom"
      :rules="rule"
      :label-width="95">
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="menuCode" :label="$t('module.menu.menuCode')">
            <Input
              disabled
              placeholder
              
              v-model.trim="modelForm.menuCode"
              style="width:100%"
            ></Input>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="menuName" :label="$t('module.menu.menuName')">
            <Input
              disabled
              placeholder
              
              v-model.trim="modelForm.menuName"
              :maxlength="50"
              style="width:100%"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="menuType" :label="$t('module.menu.menuType')">
            <Select v-model="modelForm.menuType" style="width:100%"  disabled>
              <Option
                v-for="menuType in menuTypeList"
                :value="menuType.vsiKey"
                :key="menuType.vsiKey">
                {{menuType.vsiValue}}
              </Option>
            </Select>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="enabled" :label="$t('common.status') ">
            <RadioGroup v-model="modelForm.enabled" size="small" >
              <Radio :label="1" disabled>
                <span>{{ $t("common.enable") }}</span>
              </Radio>
              <Radio :label="0" disabled>
                <span>{{ $t("common.disable") }}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="effectBegin" :label="$t('module.menu.effectBeginTime')">
            <DatePicker
              disabled
              type="date"
              ref="effectBegin"
              :placeholder="$t('module.menu.selectDate')"
              :value="modelForm.effectBegin"
              @on-change="onStartDateChange"
              :options="startDateOptions"
              :transfer="true"
              :editable="false"
              :clearable="false"
              placement="bottom-end"
              style="width: 100%;"
              
            ></DatePicker>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="effectEnd" :label="$t('module.menu.effectEndTime')">
            <DatePicker
              disabled
              type="date"
              ref="effectEnd"
              :placeholder="$t('module.menu.permanent')"
              :value="modelForm.effectEnd"
              @on-change="onEndDateChange"
              :options="endDateOptions"
              :transfer="true"
              :editable="false"
              :clearable="false"
              placement="bottom-end"
              style="width: 100%;"
              
            ></DatePicker>
          </Form-item>
        </Col>
      </Row>
      <!-- 备注 改为 描述 -->
      <Form-item :label="$t('common.describe')">
        <Input
          disabled
          placeholder
          type="textarea"
          :rows="4"
          
          v-model="modelForm.remark"
          :maxlength="100"
          style="width:100%"
        ></Input>
      </Form-item>
    </Form>
    <Row >
        <Col span="24">
            <Card 
                :bordered="true"
                :shadow="false"
                :dis-hover="true">
                <p slot="title" style="background: #eeeeee;">{{ $t("module.menu.assignedFeature") }}</p>
                  <el-tree
                    class="assignedTree treeStyle"
                    icon-class="ivu-icon-ios-arrow-forward"
                    :data="assignedData"
                    :props="treeProps"
                    node-key="key"
                    >
                  </el-tree>
            </Card>
        </Col>
    </Row>
  </div>
</template>
<script>
import valueSetAPI from "@/api/valueSetAPI.js";
import menuAPI from "@/api/menuAPI.js";
import { searchAppList } from "@/api/applicationApi.js";
import locales from "./locales.js";
import { codeReg } from "@/const.js";

// 一天的毫秒数
const ONE_DAY = 86400000;
export default {
  name: "menu-edit",
  mixins: [locales],
  components: {},
  props: {
    menuId: {
      type: String,
      default() {
        return "";
      }
    },
    tenantCode: {
      type: String,
      default() {
        return "";
      }
    },
    rowList: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    const validateMenuCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.menu.warning.enterMenuCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };
    return {
        appList: {},
        assignedData: [],
        treeProps: {
          label: "title",
          children: "children"
        },
        modelForm: {
        menuName: "",
        remark: "",
        id: "",
        effectBegin: "",
        effectEnd: "",
        menuCode: "",
        menuType: 1,
        tenantCode: null,
        enabled: 1
      },
      rule: {
        menuCode: [{ validator: validateMenuCode, trigger: "blur", required: true }],
        menuName: [
          {
            required: true,
            message: this.$t("module.menu.warning.enterMenuName"),
            trigger: "blur"
          }
        ],
        menuType: [
          {
            required: true,
            message: this.$t("module.menu.warning.enterMenuName"),
            trigger: "change"
          }
        ],
        effectBegin: [{ required: true, type: "string", trigger: "change" }],
        effectEnd: [{ required: true, type: "string", trigger: "change" }]
      },
      menuTypeList: [],
      actions: [
        {
          text: this.$t("common.close"),
          theme: "primary",
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  computed: {
    startDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.modelForm.effectEnd == "object") {
            // 日期是日期对象，如 new Date()
            return (
              date &&
              date.valueOf() < Date.now() - ONE_DAY &&
              date.valueOf() > _this.modelForm.effectEnd.valueOf() - ONE_DAY
            );
          } else if (typeof _this.modelForm.effectEnd == "string") {
            // 日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.modelForm.effectEnd.replace(/-/g, "/");
            let endDate = new Date(formatStr);
            return date && (date.valueOf() < Date.now() - ONE_DAY || date.valueOf() > endDate.valueOf());
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    },
    endDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.modelForm.effectBegin == "object") {
            // 生效日期是日期对象，如 new Date()
            return date && date.valueOf() < _this.modelForm.effectBegin.valueOf() - ONE_DAY;
          } else if (typeof _this.modelForm.effectBegin == "string") {
            // 生效日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.modelForm.effectBegin.replace(/-/g, "/");
            let startDate = new Date(formatStr);
            return date && date.valueOf() < startDate.valueOf();
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    }
  },
  created: function() {
    this.$emit("SetTitle", this.$t("module.menu.detail"));
    this.$emit("SetPageWidth", 700);
    this.$emit("SetPageActions", this.actions);
  },
  mounted: function() {
    this.init();
    this.queryResourceTree()
  },
  methods: {
    async queryResourceTree() {
      const [
        {
          data: { records }
        },
        assignedTree
      ] = await Promise.all([
        searchAppList({ pageNum: 1, pageSize: 200 }),
        menuAPI.queryAssignedResourceTree(this.menuId)
      ]);
      this.isQuery = false;

      // 初始化应用
      this.initApplication(records);

      // 初始化已分配资源树
      const assignedData = this.initChildren(assignedTree) || [];
      this.assignedData = this.groupByApp(assignedData);
    },
    // 获取资源树
    queryAssignedResourceTree() {
      menuAPI.queryAssignedResourceTree(this.menuId).then(treeData => {
        const assignedData = this.initChildren(treeData) || [];
        this.assignedData = this.groupByApp(assignedData);
      });
    },
    // 获取应用
    initApplication(records) {
      records.forEach(app => {
        this.appList[app.clientId] = app.appName;
      });
    },
    groupByApp(datas) {
      // 功能按应用分类
      const source = datas.reduce((apps, item) => {
        Array.isArray(apps[item.applicationCode]) || (apps[item.applicationCode] = []);
        // apps[item.applicationCode].push(item);
        // isShow: 1和null为显示功能（存在的功能）,0为隐藏功能（不存在的功能）
        if (item.isShow != 0) {
          apps[item.applicationCode].push(item);
        }
        return apps;
      }, {});
      //
      const newDatabase = [];
      for (const [key, val] of Object.entries(source)) {
        newDatabase.push({
          id: key == "" ? "public" : key,
          key: key == "" ? "public" : key,
          title: key == "" ? this.$t("module.menu.publicFunction") : this.appList[key] || key,
          children: val,
          first: true
        });
      }
      return newDatabase;
    },
    initChildren(children) {
      children.forEach(node => {
        node.key = node.id;
        if (node.menuType == "1") {
          // 当前节点是菜单目录
          node.children = this.initChildren(node.menuChildren);
          node.title = node.menuName;
        } else if (node.menuType == "0") {
          // 当前节点是菜单
          node.children = this.initChildren(node.resourceChildren);
          node.title = node.menuName;

          // // 已分配节点不可勾选
          // if (!this.isRightTree) {
          //   node.disabled = this.isAssignedNode(this.assignedData, node);
          //   // 已分配节点为选中状态
          //   if (node.disabled == true) {
          //     this.defaultCheckedKeys.push(node.id);
          //   }
          // }
        } else if (node.resourceType) {
          // 当前节点是资源
          node.children = this.initChildren(node.resourceChildren);
          node.title = node.resourceName;

          // // 已分配节点不可勾选
          // if (!this.isRightTree) {
          //   node.disabled = this.isAssignedNode(this.assignedData, node);
          //   // 已分配节点为选中状态
          //   if (node.disabled == true) {
          //     this.defaultCheckedKeys.push(node.id);
          //   }
          // }

          // 当前节点是API资源
          if (node.resourceType == 2) {
            // 使用父Id+子Id作为key
            // 因为有资源挂载功能，API资源可能重复出现，导致id相同的节点出现
            node.key = node.parentResourceId + node.id;
          }
        } else {
          // 当前节点是未知类型
          node.children = this.initChildren(node.menuChildren);
          node.title = node.menuName;
        }
        // 勾选的节点
        if (node.selected == 1) {
          this.checkedList.push(node.key);
        }
      });

      return children;
    },
    init() {
      if (this.menuId) {
        this.modelForm = Object.assign(this.rowList, {
          effectBegin: this.formatDateTime(this.rowList.effectBegin),
          effectEnd: this.rowList.effectEnd == null ? "" : this.formatDateTime(this.rowList.effectEnd)
        });
      } else {
        // 默认有效期
        // this.modelForm.effectBegin = this.formatDateTime(new Date()).trim();
        this.modelForm.effectBegin = new Date()
          .toISOString()
          .replace(/T.*/, " ")
          .trim();
        this.modelForm.effectEnd = "2099-12-31";
      }
      this.initTenant();
      this.initMenuType();
      // this.queryResourceTree()
    },
    // 补零
    addZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 格式化时间
    formatDateTime(date) {
      var time = new Date(Date.parse(date));
      time.setTime(time.setHours(time.getHours() + 8));
      var Y = time.getFullYear() + "-";
      var M = this.addZero(time.getMonth() + 1) + "-";
      var D = this.addZero(time.getDate()) + " ";
      var h = this.addZero(time.getHours()) + ":";
      var m = this.addZero(time.getMinutes()) + ":";
      var s = this.addZero(time.getSeconds());
      return Y + M + D;
    },
    onStartDateChange(date) {
      this.modelForm.effectBegin = date;
    },
    onEndDateChange(date) {
      this.modelForm.effectEnd = date;
    },
    // 初始化所属租户
    initTenant() {
      // 新增菜单时
      if (this.menuId == "" && this.tenantCode) {
        this.modelForm.tenantCode = this.tenantCode;
      }
    },
    // 初始化菜单类型
    initMenuType() {
      valueSetAPI.getValueSetByCode("SYS_MENU_TYPE").then(data => {
        this.menuTypeList = data;
      });
    }
  }
};
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  padding-right: 8px;
}
.ivu-form .ivu-form-item-label {
  padding: 10px 9px 10px 0 !important;
}
.ivu-card-head{
    background: #eee;
}
</style>
